package com.wanxi.controller;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ImgDTO;
import com.wanxi.dto.ResultDTO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.io.*;
import java.nio.file.Paths;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * 文件
 * @Author : 林子淳
 * @create 2023/3/13 14:01
 */
@RestController
public class UploadServlet {
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    /**
     * 上传数据及保存文件
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @PostMapping("/upload")
    @CrossOrigin
    protected ResultDTO upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultDTO resultDTO = null;
        // 检测是否为多媒体上传
        if (multipartFile == null && multipartFile.isEmpty()) {
            resultDTO = ResultDTO.getResult("Error: 表单必须包含 enctype=multipart/form-data");
            return resultDTO;
        }
        //1，获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //2,截取源文件的文件名前缀,不带后缀
        String fileNamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        //3,加工处理文件名，原文件加上时间戳
        String newFileNamePrefix = fileNamePrefix + System.currentTimeMillis();
        //4,得到新文件名
        String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));
        //5.获取文件从前端传过来的文件路径
        String uploadPath = request.getServletContext().getRealPath("./") + "/" + UPLOAD_DIRECTORY;
        //6.设置文件保存的文件名称
        String filePath = uploadPath + "/" + newFileName;
        //把文件路径放到File中
        File storeFile = new File(filePath);
//        //springMVC访问资源文件，资源文件在resources/static下，方法二；
//        //获取文件路径把文件路径放到自己想要保存的文件中
//        String path = storeFile.getPath().split("out")[0] + "src/main/resources/static";
//        createDirectory(path);
//        //通过路径保存到新的文件中
//        File file = new File(path, newFileName);
//        //保存文件
//        multipartFile.transferTo(file);
//        resultDTO = ResultDTO.getResult("上传成功", 1, new ImgDTO("http://127.0.0.1:8080/"+newFileName));

        //springMVC访问资源文件，资源文件在web下,方法一；
        //保持文件到默认缓存路径中out中
        multipartFile.transferTo(storeFile);
        //获取文件路径把文件路径放到自己想要保存的文件中
        String path = storeFile.getPath().split("out")[0] + "/web/" + UPLOAD_DIRECTORY;
        //判断文件存不存在，不存在就创建文件
        createDirectory(path);
        //通过路径保存到新的文件中
        File file = new File(path, newFileName);
        //保存文件
        multipartFile.transferTo(file);
        resultDTO = ResultDTO.getResult("上传成功", 1, new ImgDTO("http://127.0.0.1:8080/"+ UPLOAD_DIRECTORY + "/" +newFileName));

        /*String uploadPath = request.getServletContext().getRealPath("./") + "/" + UPLOAD_DIRECTORY;
        createDirectory(uploadPath);
        try {
            //文件保存的绝对路径
            String filePath = uploadPath + "/" + newFileName;
            File storeFile = new File(filePath);
            multipartFile.transferTo(storeFile);

            // 在控制台输出文件的上传路径
            System.out.println(filePath);
            // 拷贝一份文件到web目录下
//        String path = storeFile.getPath().split("out")[0] + "/web/" + UPLOAD_DIRECTORY + "/";
            copyFile(storeFile, newFileName);

//        resultDTO = ResultDTO.getResult("", 1, new ImgDTO("/" + UPLOAD_DIRECTORY + "/" + newFileName));
            resultDTO = ResultDTO.getResult("上传成功", 1, new ImgDTO("/" + UPLOAD_DIRECTORY + "/" + newFileName));
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }*/
        return resultDTO;
    }

    private void createDirectory(String uploadPath) {
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    }

    private void copyFile(File storeFile, String fileName) {
        String path = storeFile.getPath().split("out")[0] + "/web/" + UPLOAD_DIRECTORY;
        createDirectory(path);
        File file = new File(path, fileName);
        try (InputStream inputStream = new FileInputStream(storeFile);
             OutputStream outputStream = new FileOutputStream(file);) {
            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

